/**
 * Copyright (C) 2013 DaiKit.com - daikit4gxt module (admin@daikit.com)
 *
 *         Project home : http://code.daikit.com/daikit4gxt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.daikit.daikit4gxt.client.action;

import com.daikit.daikit4gxt.client.DkBaseMain;
import com.daikit.daikit4gxt.client.log.DkLogger;
import com.daikit.daikit4gxt.client.ui.popup.DkMessageBox;
import com.google.gwt.user.client.Timer;
import com.sencha.gxt.fx.client.DragEndEvent;
import com.sencha.gxt.fx.client.DragEndEvent.DragEndHandler;
import com.sencha.gxt.widget.core.client.box.ProgressMessageBox;


/**
 * The {@link DkBaseAction} progress dialog
 * 
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 */
public class DkBaseActionProgressDialog
{

	private static final DkLogger LOG = DkLogger.getLog(DkBaseActionProgressDialog.class);

	private static DkBaseActionProgressDialog instance = new DkBaseActionProgressDialog();

	private final ProgressMessageBox messageBox;
	private int incrementIndex;
	private Timer fDialogTimer;
	private boolean enableTimeout;
	private String message;

	private DkBaseActionProgressDialog()
	{
		messageBox = new ProgressMessageBox(DkBaseMain.i18n().action_title());
		setMessage(DkBaseMain.i18n().action_default_message());
		messageBox.setModal(true);
		messageBox.setMinWidth(300);
		incrementIndex = 0;
		messageBox.getDraggable().addDragEndHandler(new DragEndHandler()
		{
			@Override
			public void onDragEnd(final DragEndEvent event)
			{
				if (nbStepToIgnore == 0 && incrementIndex == 0)
				{ // Should be closed.
					close();
				}
			}
		});
		messageBox.setPredefinedButtons();
	}

	/**
	 * @return the unique instance of this {@link DkBaseActionProgressDialog}
	 */
	public static DkBaseActionProgressDialog get()
	{
		return instance;
	}

	/**
	 * Set the progress dialog title
	 * 
	 * @param title
	 *           the title to set
	 */
	public void setTitle(final String title)
	{
		messageBox.setTitle(title);
	}

	/**
	 * Set the progress dialog message
	 * 
	 * @param message
	 *           the message to set
	 */
	public void setMessage(final String message)
	{
		this.message = message;
		messageBox.setMessage(message);
	}

	/**
	 * @return the progress dialog message
	 */
	public String getMessage()
	{
		return message;
	}

	/**
	 * Set the progress dialog text (within the progress bar)
	 * 
	 * @param progressText
	 *           the progress text
	 */
	public void setProgressText(final String progressText)
	{
		messageBox.setProgressText(progressText);
	}

	/**
	 * @return the progress dialog current title
	 */
	public String getTitle()
	{
		return messageBox.getTitle();
	}

	/**
	 * @return the progress dialog current text
	 */
	public String getProgressText()
	{
		return messageBox.getProgressText();
	}

	/**
	 * @return whether timeout is enabled
	 */
	public boolean isEnableTimeout()
	{
		return enableTimeout;
	}

	/**
	 * @param enableTimeout
	 *           a boolean indicating whether the client side timeout has to be handled
	 */
	public void setEnableTimeout(final boolean enableTimeout)
	{
		this.enableTimeout = enableTimeout;
	}

	/**
	 * Increment the progress bar by one step
	 * 
	 * @param action
	 *           the new action to be executed
	 * @param message
	 *           the message to be displayed in the incremented step progress bar
	 */
	public void increment(final DkBaseAction<?> action, final String message)
	{
		if (nbStepToIgnore == 0 && incrementIndex++ == 0)
		{ // hidden
			setTitle(DkBaseMain.i18n().action_title());
			setProgressText("");
			show();
		}
		resetTimeoutTimer();
		if (enableTimeout)
		{
			fDialogTimer = new Timer()
			{
				@Override
				public void run()
				{
					LOG.info("Action [" + message + "] timeout.");
					action.stopBecauseOfTimeout();
					DkMessageBox
							.alert(
									"Action Timeout",
									"Action ["
											+ message
											+ "] Timeout. Please verify your internet connection. Reconnect and contact an administrator if the problem persists.",
									null);
				}
			};
			fDialogTimer.schedule(DkBaseMain.config().getActionTimeoutMilliseconds());
		}
		messageBox.updateProgress(new Double(incrementIndex) / new Double(DkActionChainExecutor.get().getNumberOfSteps()), message);
		messageBox.toFront();
	}

	protected int nbStepToIgnore = 0;

	/**
	 * Reset the timeout timer (called by action when a step has finished or when incrementing the progress dialog)
	 */
	public void resetTimeoutTimer()
	{
		if (enableTimeout && fDialogTimer != null)
		{
			fDialogTimer.cancel();
			fDialogTimer = null;
		}
	}

	/**
	 * End a chain action step. When an action isn't showing its progress, the progress dialog has to know that these
	 * action have been executed in order to know when to be hidden.
	 * 
	 * @param nbStepToIgnoreAdded
	 */
	public void endStep(final int nbStepToIgnoreAdded)
	{
		resetTimeoutTimer();
		nbStepToIgnore += nbStepToIgnoreAdded;
		if (nbStepToIgnore == 0 || --nbStepToIgnore == 0)
		{
			if (incrementIndex >= DkActionChainExecutor.get().getNumberOfSteps())
			{
				messageBox.updateProgress(1, "{0}" + DkBaseMain.i18n().action_update_progress_text());
				close();
			}
		}
	}

	private void show()
	{
		messageBox.show();
	}

	/**
	 * Close the progress dialog
	 */
	public void close()
	{
		incrementIndex = 0;
		nbStepToIgnore = 0;
		if (messageBox.getProgressBar() != null)
		{
			messageBox.getProgressBar().reset();
		}
		if (fDialogTimer != null)
		{
			fDialogTimer.cancel();
		}
		if (messageBox.isVisible())
		{
			messageBox.hide();
		}
	}

	/**
	 * Reset the progress dialog
	 */
	public void reset()
	{
		close();
	}

	/**
	 * Retrieve the number of steps to be ignored
	 * 
	 * @return the number of steps to be ignored
	 */
	public int getNbStepToIgnore()
	{
		return nbStepToIgnore;
	}
}
